package com.example.pageradapterdemo.fragment;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public abstract class CommonPageAdapter<T> extends PagerAdapter {
    protected LayoutInflater mInflater;
    protected List<T> mDataList;
    private SparseArray<View> views;

    public CommonPageAdapter(Context context,List<T> mDataList) {
        mInflater = LayoutInflater.from(context);
        this.mDataList = mDataList;
        this.views = new SparseArray<>(mDataList.size());
    }

    @Override
    public int getCount() {
        return mDataList == null ? 0: mDataList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = views.get(position);
        if (view == null) {
            view = getView(position);
            views.put(position,view);
        }
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.destroyItem(container, position, object);
    }
    public abstract View getView(int position);
}
